#!/usr/local/bin/python
# -*- coding: utf-8 -*-

from functools import wraps
from flask import session, url_for, redirect, request
from model import Design, Unit, Design_Type
Usercode = 1

def q(string):
    """
    adds quotes before and after a string
    """    
    return "\"" + str(string) + "\""


def table(l, id="table_id"):
    """
    creates a table with headers and footers ready to be used with
    datatables
    """
    s="<table id=\""+id+"\">"
    s+="<thead><tr>"
    for i in l:
        s+="<th>" + str(i) + "</th>"
    s+="</tr></thead>"
    s+="<tbody></tbody>"
    s+="<tfoot><tr>"
    for i in l:
        s+="<th>" + str(i) + "</th>"
    s+="</tr></tfoot>"
    s+="</table>"
    return s
    
    
def login_required(f):
    """
    if the user is not logged in, redirects to the start screen
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not session.has_key('Usercode'):
            return redirect(url_for('start_screen'))
        return f(*args, **kwargs)
    return decorated_function


def get2parameters(f):
    """
    passes the GET args as parameters to the page function
    """
    @wraps(f)
    def decorated_function():
        a=request.args
        return f(**(a.to_dict()))
    return decorated_function


def formtable(tup, hidden=None, action=None, attr=[]):
    """
    forms a simple table with a dict of forms
    """
    s = "<form"
    for i in attr:
        s += (" "+ i +" ")
    if action:
        s += " action=" + q(action)
    s += " >\n"
    if hidden:
        for i in hidden:
            s+=i+"\n"
    s += "<table>\n"
    for i in tup:
        s += "<tr><td>"
        s += i[0] +": "
        s += "</td><td>"
        s += i[1]
        s += "</td></tr>\n"
    s += """<tr><td></td><td><input type="submit"></td></tr>"""
    s += "</table></form>\n"
    return s


def textinput(name="", value="", ID="", readonly=False):
    """
    creates a text input
    """
    s="<input "
    if name:
        s+="name="+q(name)+" "
    if value:
        s+="value="+q(value)+" "
    if ID:
        s+="Id="+q(ID)+" "
    if readonly:
        s+="readonly=True "

    s+="/>\n"
    return s
    
    
def options(l=[], name="", default=""):
    """
    generates a list of options for a html form
    """
    s="<select "
    if name:
        s+="name=" + q(name)
    s+=">"
    for i in l:
        s+=" <option value=" + q(i[0])
        if default==i[0]:
            s += """" selected = "true" """
        s+=">" + i[1] + "</option>"
    s+="</select>"
    return s


def unitoptions(name="", default=""):
    """
    returns a form select field with all the units
    """
    default=str(default)
    s = "<select "
    if name:
        s+="name="+q(name)

    for i in Unit.query.all():
        s+= "<option value=" + q(i.ID_Unit)
        if str(i.ID_Unit) == default:
            s += """" selected = "true" """
        s+= ">" + i.descr() + "</option>"
    
    s+="</select>"
    return s
    

def designoptions(name="", default="", hidden=[], types=[], current=True):
    """
    returns a form select field with all the designs
    """
    default=str(default)
    s="<select "
    if name:
        s+="name="+q(name)
    s+=">"
    for i in Design.query.all():
        if current:
            if (not i.ID_Design in hidden ) and (i.ID_Design_Type in types) and i.isCurrent():
                s+="<option value=" + i.ID_Design 
                if str(i.ID_Design) == default:
                    s += """" selected = "true" """
                s+= ">" + i.Description_Std+ "</option>"
        else:
            if (not i.ID_Design in hidden ) and (i.ID_Design_Type in types):
                s+="<option value=" + i.ID_Design 
                if str(i.ID_Design) == default:
                    s += """" selected = "true" """
                s+= ">" + i.Description_Std+ "</option>"            
    s+="</select>"
    return s


def typeoptions(name="", default=""):
    """
    returns a form select field with all the types
    """
    default=str(default)
    default=str(default)
    s = "<select "
    if name:
        s+="name="+q(name)

    for i in Design_Type.query.all():
        s+= "<option value=" + q(i.ID_Design_Type)
        if str(i.ID_Design_Type) == default:
            s += """" selected = "true" """
        s+= ">" + i.descr() + "</option>"
    
    s+="</select>"
    return s


def link(href="",text=""):
    return "<a href=\"" + str(href) + "\">"+ str(text) + "</a>"


def writeBarCode(ID_Design, Bar_Code):
    s1=str(ID_Design)[-4:]
    s2=str(Bar_Code).zfill(7)
    s=s1+s2
    x = 0
    for i in s[1::2]:
       x += int(i)
    y = 0
    for i in s[::2]:
        if 2*int(i)>9:
            y+=(2*int(i))-9
        else:
            y+=(2*int(i))
    z=x+y
    t=z%10
    d=10-t
    if d==10:
        d=0
    return d

















